#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : bigDataProject 
@File    : base_api.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/11/11 14:52 
@Describe: 接口请求基类
"""
from typing import Text, Union

import requests

from api.model.enum.api_error_enum import API_ERROR_ENUM
from model.exceptions import RequestFailedException
from utils.common.common_control import get_json_result, get_json_value
from utils.log.log_control import LogHandler
from utils.notice.work_wechat import send_work_wechat_message
from utils.sqlite.sqlite_control import SqliteControl


class BaseAPI(object):

    def __init__(self) -> None:
        self.logger = LogHandler().get_logger()
        self.sqlite = SqliteControl('support.db')
        self.URL: Text = ''
        self.TYPE: Text = ''

    def get_headers(self) -> None:
        pass

    def http_request(self, url: Text, payload: Text, interface_name: Union[Text, None] = None):
        """
        接口请求
        :param url: 接口URL
        :param payload: 请求参数
        :param interface_name: 接口中文名称
        :return: response or error_message
        """
        post_url = self.URL + url
        response = requests.request("POST", url=post_url, headers=self.get_headers(), data=payload)
        response_time = response.elapsed.total_seconds()
        response_code = get_json_result(response, "$.code")
        trace_id = get_json_value(response.headers, key='X-B3-TraceId')
        if interface_name is None:
            interface_name = url
        self.logger.info('*' * 20 + '接口请求开始' + '*' * 20)
        self.logger.info('接口名称:{}'.format(interface_name))
        self.logger.info('请求路径:{}'.format(post_url))
        self.logger.info('请求参数:{}'.format(payload))
        self.logger.info('接口响应信息:{}'.format(response.text))
        self.logger.info('TraceId:{}'.format(trace_id))
        if response_code == 200:
            self.logger.info('接口响应时间:{}秒'.format(response_time))
            self.logger.info('接口请求成功！')
            self.logger.info('*' * 20 + '接口请求结束' + '*' * 20)
            return response
        else:
            error_message = get_json_result(response, '$..message')
            self.logger.error('错误信息:{}'.format(error_message))
            self.logger.error('接口请求失败!')
            self.logger.info('*' * 20 + '接口请求结束' + '*' * 20)
            send_work_wechat_message(post_url, interface_name, payload, error_message, response_code, trace_id)
            result_info = API_ERROR_ENUM.SYSTEM_ERROR.value[1].format(post_url, payload, error_message, trace_id)
            raise RequestFailedException(result_info)
